package com.lsq.tomcat;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lsq
 * @description TODO
 * @date 2023/9/14
 */
public class Response extends AbstractHttpSercletResponse{
    private int status = 200;
    private String message = "ok";
    private Map<String, String> header = new HashMap<>();
    private Request request;
    private byte SP = ' ';
    private byte CR = '\r';
    private byte LF = '\n';
    private OutputStream socketOutputStream;
    private ResponseServletOutputStream responseServletOutputStream = new ResponseServletOutputStream();

    public Response(Request request) {
        this.request = request;
        try {
            this.socketOutputStream = request.getSocket().getOutputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void setStatus(int i, String s) {
        status=i;
        message=s;
    }

    @Override
    public int getStatus() {
        return status;
    }

    @Override
    public void addHeader(String s, String s1) {
        header.put(s, s1);
    }

    @Override
    public ResponseServletOutputStream getOutputStream() throws IOException {
        return responseServletOutputStream;
    }

    public void complete() throws IOException {
        sendResponseBody();
        sendResponseHeader();
        sendResponseLine();
    }

    public void sendResponseBody() throws IOException {
        //响应体
        socketOutputStream.write(getOutputStream().getBytes());
    }

    public void sendResponseHeader() throws IOException {
        if (!header.containsKey("Content-Length")){
            addHeader("Content-Length", String.valueOf(getOutputStream().getPos()));
        }

        //响应头
        for (Map.Entry<String, String> stringStringEntry : header.entrySet()) {
            String key = stringStringEntry.getKey();
            String value = stringStringEntry.getValue();
            socketOutputStream.write(key.getBytes());
            socketOutputStream.write(":".getBytes());
            socketOutputStream.write(value.getBytes());
            socketOutputStream.write(CR);
            socketOutputStream.write(LF);
        }
        socketOutputStream.write(CR);
        socketOutputStream.write(LF);
    }

    public void sendResponseLine() throws IOException {
        //发送响应行
        socketOutputStream.write(request.getProtocol().getBytes());
        socketOutputStream.write(SP);
        socketOutputStream.write(status);
        socketOutputStream.write(SP);
        socketOutputStream.write(message.getBytes());
        socketOutputStream.write(CR);
        socketOutputStream.write(LF);
    }
}
